<template>
  <div class="login-wrap">
    <div class="ms-login">
      <div class="ms-title">IWu招聘</div>
      <el-form :model="loginUser" :rules="loginRules" ref="loginForm" label-width="0px" class="ms-content">
        <el-form-item prop="email">
          <el-input v-model="loginUser.email" placeholder="请输入邮箱" :prefix-icon="Message">

          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" placeholder="请输入密码" v-model="loginUser.password"
            @keyup.enter.native="handleLogin(loginForm)" :prefix-icon="Lock">
          </el-input>
        </el-form-item>
        <el-form-item prop="code_1">
          <div class="codeItem">
            <el-input type="text" style="width: 200px;" v-model="loginUser.code_1" placeholder="请输入验证码" />
            <!-- <template v-slot="suffix"> -->
            <div class="codePicture" @click="refreshCode">
              <CanvasCode class="codePicture1" :identifyCode="codeData.identifyCode"></CanvasCode>
            </div>
          </div>

          <!-- </template> -->
        </el-form-item>
        <el-form-item label="">
          <el-radio-group v-model="loginUser.role">
            <el-radio label="user">个人</el-radio>
            <el-radio label="enterprise">企业</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="login-btn">
          <el-button type="primary" @click="handleLogin(loginForm)">登录</el-button>
        </div>
        <!-- 注册 -->

        <p class="login-tips">Tips : 没有账号? <a href="/register">注册</a></p>
      </el-form>
    </div>
  </div>
</template>
<script lang='ts'>
import { Lock, Message } from "@element-plus/icons-vue"
import { reactive, getCurrentInstance, ref, onBeforeMount } from 'vue'
import { elmessage } from "@/hook/hook"
import { useRoute, useRouter } from 'vue-router';
import { loginUser, loginRules } from "@/utills/loginValidators";
import Header from "@/components/Header.vue";
import CanvasCode from "@/components/CanvasCode.vue"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus';
import { useStore } from "vuex"
import { login } from "@/api/authApi"
export default {
  name: "Login",
  components: { Header, CanvasCode },
  setup() {

    //创建store对象
    const store = useStore()
    // 登录
    // @ts-ignore
    const { proxy } = getCurrentInstance() // 1.获取proxy实例

    // 登录表单
    const loginForm = ref<FormInstance>()

    const router = useRouter()
    const codeData = reactive({
      identifyCodes: '1234567890abcdefjhijk1234567890linopqrsduvwxyz', // 验证码组成元素
      identifyCode: '', // 验证码生成结果
      code: '', // 验证码输入内容
    })
    // 重置验证码
    const refreshCode = () => {
      codeData.identifyCode = ''
      makeCode(codeData.identifyCodes, 4)
      loginUser.code_2=codeData.identifyCode
      // console.log(data.identifyCode);

    }
    const makeCode = (o: any, l: any) => {
      // o代表随机数元素集合，l代表验证码位数（现在为4位验证码）
      for (let i = 0; i < l; i++) {
        codeData.identifyCode += codeData.identifyCodes[randomNum(0, codeData.identifyCodes.length)]
      }

    }
    const randomNum = (min: number, max: number) => {
      return Math.floor(Math.random() * (max - min) + min)
    }
    // 触发登录方法  async异步
    const handleLogin = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      // 点击按钮触发表单验证
      await formEl.validate(async (valid: any) => {

        if (valid) {
          // 表单数据解构成字典
          const data = {
            ...loginUser
          }
         
          await login(data).then(
            async (res: any) => {
              if (res.data["type"] === "success") {
                // 注册成功跳转主页
                elmessage(res.data["message"], res.data["type"])
                // console.log(res.data);
                // 本地存储登录状态
                await localStorage.setItem("loginData", JSON.stringify({ "loginId": res.data.loginId, "token": res.data.token, "identity": res.data.identity }))
                // console.log(localStorage);

                await store.commit("loginState", res.data)
                setTimeout(() => {
                  if (res.data["identity"] == "user") {
                    router.push("/")
                  } else if (res.data["identity"] == "enterprise") {
                    router.push("/enterprisehome")
                  }
                }, 500);
              }
              else {

                elmessage(res.data["message"], res.data["type"])
                return false
              }
            }

          )
          formEl.resetFields()
        } else {
          return false;
        }
      });
    };

    onBeforeMount(() => {
      refreshCode()
    })
    return {
      loginUser,
      loginRules,
      loginForm,
      codeData,
      refreshCode,
      handleLogin,
      Lock, Message,
    };
  },

}
</script>
<style lang="css" scoped>
a {
  text-decoration: none;
}

a:hover {
  text-decoration: underline !important;
}

.login-wrap {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-size: cover;
  background-image: url("@/assets/loginRegister/loginBg.jpeg");

}

.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #000;
  border-bottom: 1px solid #FFF;
}

.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 370px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}

.ms-content {
  padding: 30px 30px;
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}

.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}

.codeItem {
  width: 310px;
  /* display: inline-flex; */
  float: auto;
}

.codePicture {
  width: 100px;
  height: 30px;
  text-align: center;
  float: right;
  /* margin-left: 4px; */
  /* margin: 5px 30px; */
  border: 2px solid #009199;
}

.codePicture1 {
  float: right;
  width: 100px;
  height: 30px;
}
</style>